<template>
  <div class="app-container">
    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button v-hasPerm="['sys:dept:add']" type="success" @click="handleOpenDialog(0)">
          <template #icon><i-ep-plus /></template>
          新增
        </el-button>
        <el-button v-hasPerm="['sys:dept:query']" type="primary" @click="handleQuery()">
          <template #icon><i-ep-refresh /></template>
          刷新
        </el-button>
      </template>
      <el-table
        v-loading="loading"
        :data="list"
        :lazy="true"
        :stripe="true"
        :indent="10"
        highlight-current-row
        default-expand-all
        row-key="id"
        @row-click="handleRowClick"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <!-- <el-table-column label="ID" width="50" prop="id" min-width="50" /> -->
        <el-table-column label="机构名称" width="300" prop="name" min-width="100" />
        <el-table-column label="状态" width="100" prop="enabled" min-width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.enabled" type="success">使用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="200" prop="createTime" min-width="100" />
        <el-table-column label="排序" width="100" prop="orderNum" min-width="100" />

        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:dept:update']"
              link
              type="primary"
              size="small"
              @click.stop="handleOpenDialog(scope.row.pid, scope.row.id)"
            >
              <i-ep-edit />
              修改
            </el-button>
            <el-button
              v-hasPerm="['sys:dept:delete']"
              type="danger"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-drawer v-model="dialog.visible" :title="dialog.title" @close="handleCloseDialog" size="50%">
      <el-form ref="addFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="父级菜单" prop="pid">
          <el-tree-select
            v-model="formData.pid"
            placeholder="选择上级机构"
            :data="deptTreeOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="机构名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入机构名称" />
        </el-form-item>

        <el-form-item label="排序" prop="orderNum">
          <el-input-number
            v-model="formData.orderNum"
            style="width: 100px"
            controls-position="right"
            :min="0"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="formData.enabled">
            <el-radio :value="true">有效</el-radio>
            <el-radio :value="false">无效</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
defineOptions({
  name: 'Dept',
  inheritAttrs: false
})

import { ElForm, ElTable } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'

const list = ref([])
const loading = ref(false)
const deptTreeOptions = ref()
const dialog = reactive({
  visible: false,
  title: '添加机构'
})
const addFormRef = ref(ElForm)
const formData = ref({
  id: '',
  pid: 0,
  name: '',
  code: '',
  orderNum: 100,
  remark: '',
  enabled: true
})
const BASE_URL = '/api/yyplatform/admin/sys/dept/'
const rules = ref({
  pid: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  orderNum: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})
async function handleOpenDialog(pid, id) {
  console.log('handleOpenDialog', pid)

  let res = await request({
    url: `${BASE_URL}/options`,
    method: 'get'
  })
  console.log('res=>', res)

  deptTreeOptions.value = [{ value: '0', label: '顶级机构', children: res }]
  if (id) {
    dialog.visible = true
    dialog.title = '修改机构'

    let detailRes = await request({
      url: `${BASE_URL}/get?id=${id}`,
      method: 'get'
    })
    formData.value = detailRes
    // todo
  } else {
    dialog.visible = true
    dialog.title = '添加机构'
    formData.value = {
      pid: '0',
      id: '',
      name: '',
      code: '',
      orderNum: 100,
      remark: '',
      enabled: true
    }
  }
}

function submitForm() {
  addFormRef.value.validate((isValid) => {
    if (isValid) {
      const id = formData.value.id
      if (id) {
        request({
          url: `${BASE_URL}/update`,
          method: 'post',
          data: formData.value
        }).then((res) => {
          ElMessage.success('修改成功')
          handleCloseDialog()
          handleQuery()
        })
      } else {
        request({
          url: `${BASE_URL}/save`,
          method: 'post',
          data: formData.value
        }).then((res) => {
          ElMessage.success('添加成功')
          handleCloseDialog()
          handleQuery()
        })
      }
    }
  })
}

function handleCloseDialog() {
  dialog.visible = false
}

function handleDelete(id) {
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request({
      url: `/api/yyplatform/admin/sys/dept/delete`,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: {
        id: id
      }
    }).then(() => {
      handleQuery()
    })
  })
}

function handleQuery() {
  loading.value = true
  request({
    url: '/api/yyplatform/admin/sys/dept/query',
    method: 'get',
    params: {}
  }).then((res) => {
    console.log(res, 'res')

    loading.value = false
    list.value = res
  })
}
onMounted(() => {
  handleQuery()
})
</script>
